package top.codedance.iotp.manage.client.handler;

import top.codedance.iotp.common.constent.Command;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.manage.Console;
import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class ServerReponseHandler extends SimpleChannelInboundHandler<CommonEntity> {

    protected void messageReceived(final ChannelHandlerContext channelHandlerContext, final CommonEntity commonEntity) throws Exception {
        if(Arrays.asList(Command.CONSOLE_MANAGE_COMMAND_RECEIVE, Command.REGISTER_RECEIVE).contains(commonEntity.getCommand())) {
            String result = new String(commonEntity.getBody(), StandardCharsets.UTF_8);
            Console.syslogInfo(result);
        }else{
            CommonEntity commonEntity2 = new CommonEntity();
            commonEntity2.setVersion(commonEntity.getVersion());
            commonEntity2.setCommand(Command.NONE);
            commonEntity2.setBody("unauthorized operation".getBytes(StandardCharsets.UTF_8));
            channelHandlerContext.writeAndFlush(commonEntity2);
        }
        channelHandlerContext.fireChannelRead(commonEntity); //向后传递
    }
}
